﻿using CRL.Core;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CRL.Core.Extension;
namespace CRL.RequestReport
{
    public class RequestCount
    {
        static RequestCountBase instance;
        static RequestCount()
        {
            instance = CountService.GetInstance("default");
        }
        public static void Add(string name, string type = "", int count = 1)
        {
            instance.Add(name, type, count);
        }
        public static Dictionary<string, long> GetSumByName(int passSecond, string type = "")
        {
            return instance.GetSumByName(passSecond, type);
        }
        public static Dictionary<string, long> GetSumByType(int passSecond, string name = "")
        {
            return instance.GetSumByType(passSecond, name);
        }
        public static void Clear()
        {
            CountService.Clear();
        }
        public static IDictionary<string, Dictionary<string, long>> ConvertDic(IDictionary<string, long> dic, char split)
        {
            return CountService.ConvertDic(dic, split);
        }
    }
    public class RequestCountBase
    {
        List<timeObj2> countDetails = new List<timeObj2>();
        List<timeObj2> countTotal = new List<timeObj2>();
        object lockObj = new object();
        string _name;
        internal RequestCountBase(string name)
        {
            _name = name;
           
        }
        //internal void Start()
        //{
        //    new ThreadWork().Start($"ReceiveTimeCount_{_name}", () =>
        //    {
        //        var time = DateTime.Now.AddMinutes(-60);
        //        countDetails.RemoveAll(b => b.time < time);
        //        return true;
        //    }, 60);
        //}
        internal void ClearTimeout()
        {
            var time = DateTime.Now.AddMinutes(-60);
            countDetails.RemoveAll(b => b.time < time);
        }
        public void Add(string name, string type = "", int count = 1)
        {
            var ts = DateTime.Now - new DateTime(2022, 1, 1);
            var minuteKey = (int)ts.TotalMinutes;//以区分每分钟
            var key = $"{name}_{type}".ToLower();
            lock (lockObj)
            {
                var find1 = countDetails.Find(b => b.key == key && b.minuteKey == minuteKey);
                if (find1 == null)
                {
                    find1 = new timeObj2 { name = name, type = type, time = DateTime.Now, minuteKey = minuteKey };
                    countDetails.Add(find1);
                }
                find1.count += count;

                var find2 = countTotal.Find(b => b.key == key);
                if (find2 == null)
                {
                    find2 = new timeObj2 { name = name, type = type, time = DateTime.Now };
                    countTotal.Add(find2);
                }
                find2.count += count;
            }
        }

        /// <summary>
        /// 按名称为KEY
        /// </summary>
        /// <param name="passSecond"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public Dictionary<string, long> GetSumByName(int passSecond , string type = "")
        {
            IQueryable<timeObj2> q;
            if (passSecond > 0)
            {
                var time = DateTime.Now.AddSeconds(-passSecond);
                var ts = time - new DateTime(2022, 1, 1);
                var minuteKey = (int)ts.TotalMinutes;
                q = countDetails.AsQueryable();
                q = q.Where(b => b.minuteKey >= minuteKey);
            }
            else
            {
                q = countTotal.AsQueryable();
            }
            if(!string.IsNullOrEmpty(type))
            {
                q = q.Where(b => b.type.ToLower().StartsWith(type.ToLower()));
            }
            var data = q.GroupBy(b => b.name).Select(b => new { b.Key, total = b.Sum(x => x.count) }).ToList();
            var dic = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
            data.ForEach(b =>
            {
                dic.Add(b.Key, b.total);
            });
            return dic;
        }
        public Dictionary<string, long> GetSumByType(int passSecond, string name = "")
        {
            IQueryable<timeObj2> q;
            if (passSecond > 0)
            {
                var time = DateTime.Now.AddSeconds(-passSecond);
                var ts = time - new DateTime(2022, 1, 1);
                var minuteKey = (int)ts.TotalMinutes;
                q = countDetails.AsQueryable();
                q = q.Where(b => b.minuteKey >= minuteKey);
            }
            else
            {
                q = countTotal.AsQueryable();
            }
            if (!string.IsNullOrEmpty(name))
            {
                q = q.Where(b => b.name.ToLower().StartsWith(name.ToLower()));
            }
            var data = q.GroupBy(b => b.type).Select(b => new { b.Key, total = b.Sum(x => x.count) }).ToList();
            var dic = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
            data.ForEach(b =>
            {
                dic.Add(b.Key, b.total);
            });
            return dic;
        }
        internal void Clear()
        {
            countTotal.Clear();
        }
    }

}
